package cn.coisini.utils;

import cn.coisini.model.common.enums.ResultEnum;
import cn.coisini.model.common.exception.CustomAuthenticationException;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @author xiangshaw
 * Description: 阿里云OSS工具类
 * <a href="https://help.aliyun.com/zh/oss/developer-reference/java-installation?spm=a2c4g.11186623.0.0.f45f59d4QW3Kw7">...</a>
/*
 */

@Log4j2
@Component
public class AliOssUtil {

    @Value("${file.upload.aliyun.ENDPOINT}")
    private String endpoint;

    @Value("${file.upload.aliyun.ACCESS_KEY_ID}")
    private String accessKeyId;

    @Value("${file.upload.aliyun.ACCESS_KEY_SECRET}")
    private String accessKeySecret;

    @Value("${file.upload.aliyun.BUCKET_NAME}")
    private String bucketName;

    public String uploadFile(String objectName, InputStream in) {
        // 非空检查
        if (objectName == null || objectName.isEmpty() || in == null) {
            throw new IllegalArgumentException("ObjectName and InputStream must not be null or empty.");
        }

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String url = "";
        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, in);

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // URL组成: https://bucketName.endpoint/objectName
            url = "https://" + bucketName + "." + endpoint.replaceFirst("^https?://", "") + "/" + objectName;
        } catch (OSSException oe) {
            log.error("OSSException occurred while uploading file: {}", oe.getMessage());
            log.error("UploadFileError Code: {}, Request ID: {}, Host ID: {}", oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
        } catch (ClientException ce) {
            log.error("ClientException occurred while uploading file: {}", ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }

    // 删除阿里云 OSS 文件
    public void deleteFile(String objectName) {
        if (objectName == null || objectName.isEmpty()) {
            throw new IllegalArgumentException("ObjectName must not be null or empty.");
        }
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.deleteObject(bucketName, objectName);
            log.info("File deleted from Aliyun OSS successfully: {}", objectName);
        } catch (OSSException oe) {
            log.error("OSSException occurred while deleting file: {}", oe.getMessage());
            log.error("DeleteFileError Code: {}, Request ID: {}, Host ID: {}", oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
            throw new CustomAuthenticationException(ResultEnum.FILE_DELETE_FAIL,"Failed to delete file from Aliyun OSS: " + oe.getMessage());
        } catch (ClientException ce) {
            log.error("ClientException occurred while deleting file: {}", ce.getMessage());
            throw new CustomAuthenticationException(ResultEnum.FILE_DELETE_FAIL,"Failed to delete file from Aliyun OSS: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
